package services

import (
	"beego_blog/cache"
	"beego_blog/models"
	"log"
	"net/url"
	"strconv"
	"time"

	"github.com/astaxie/beego/orm"
	"github.com/google/uuid"
)

type UserService struct {
	baseService
}

func (c *UserService) Add(params url.Values) {
	user := models.User{}

	user.Id, _ = strconv.Atoi(params.Get("id"))
	user.Username = params.Get("username")
	user.Password = params.Get("password")

	if _, err := c.o.Insert(&user); err != nil {
		log.Println("Add err", err)
	} else {
		// todo
	}

}

func (c *UserService) Delete(params url.Values) {
	id, err := strconv.Atoi(params.Get("id"))
	if err != nil {
		// todo
	} else {
		if _, err := c.o.Delete(&models.User{Id: id}); err != nil {
			// todo
		} else {
			// todo
		}
	}
}

func (c *UserService) Query(params url.Values) []*models.User {
	users := []*models.User{}
	user := models.User{}
	Query_by_model(c.o, "id", nil, user, &users)
	return users
}

func (c *UserService) Update(params url.Values) {
	user := models.User{}

	user.Id, _ = strconv.Atoi(params.Get("id"))
	user.Username = params.Get("username")
	user.Password = params.Get("password")

	if _, err := c.o.Update(&user); err != nil {
		// todo
	} else {
		// todo
	}

}

func (c *UserService) Login(params url.Values) (bool, string) {
	user := &models.User{}

	username := params.Get("username")
	password := params.Get("password")

	cond := orm.NewCondition().And("username", username)
	err := c.o.QueryTable(new(models.User)).SetCond(cond).One(user)

	if err != nil {
		// todo
		log.Println("Login err ", err)
		return false, ""
	} else {
		log.Println("Login user.Password " + user.Password)
		if user.Password == password {
			auth_s := uuid.New().String()
			cache.Authcache.Set(auth_s, username, 30*time.Minute)
			return true, auth_s
		} else {
			return false, ""
		}
	}

}
